﻿srf_init:
	;读取配置
	global srf_default_value, mhyRegExstr, YzIni:=class_EasyIni("yz.ini"), DllFolder:=A_ScriptDir "\Lib\Dll_" (A_PtrSize=4?"x86":"x64")
	srf_default_value:={Settings:{Startingup:0, Autoupdatefg:1, Adminfg:1, bddp:0, CloudInput:0, DebugLevel:1, fuzhuma:0, SendDelay:0, SendFromClip:0, Imagine:0, MemoryDB:0, Settingsbak:"", MouseCross:0, dwxg:0
		, Magicstring:0, Superrun:0, Wordfrequency:0, fixedword:0, Learning:0, Inputscheme:"pinyin", chaojijp:0, Traditional:0, Showquanpin:0, Source:"Gitee", mhy_ch:0, mhy_sh:0, mhy_zh:0, mhy_ang:0
		, mhy_eng:0, mhy_ing:0, pinyinhunsu:0, simasp:1, wumaqc:1, wumasp:1, Different:0, IMEmode:1, ClipWindows:"", IMECnWindows:"", IMEEnWindows:"", EnSymbol:0, SaveCloud:0, ShowCode:0, Singleword:0, zigen:0}
		, Func:{CustomFuncName:"{""fanyi"":""fy"",""label"":""l"",""magic"":""s"",""mode"":""m"",""run"":""r"",""scheme"":""sc"",""soso"":""ss""}"}
		, GuiStyle:{TextFont:InStr(ListFonts(),"Microsoft YaHei UI")?"Microsoft YaHei UI":"黑体",SymbolFont:"Segoe UI Symbol", FontBold:0, FontSize:20, BorderColor:"FFFFFF", CodeColor:"FFFFFF", TextColor:"FFFFFF", BackgroundColor:"006697", ListNum:5, Textdirection:"Horizontal"
		, LogoSize:100, ToolTipStyle:(A_OSVersion="WIN_XP"?1:2), Lockedposition:0}
		, Hotkey:{Double:0, Switch:"LShift", Enterfg:2, Escfg:1, Shiftfg:2, fanyefg:"[],-="}
		, DBFile:{main:"Lib\ciku.db", extend:"Lib\ciku_extend.db"}
		, Version:{Version:"1.3.1"}}
	LoadIni()
	If !InStr(ListFonts(),TextFont)
		TextFont:=YzIni["GuiStyle","TextFont"]:="黑体"
	GUIFont:=InStr(ListFonts(),"Microsoft YaHei UI")?"Microsoft YaHei UI":"黑体", yzPID:=DllCall("GetCurrentProcessId")
	Yz_Abort:="影子输入法是由河许人和天黑请闭眼联合开发的简单、简洁、高度自定义输入法。影子输入法起源于AutoHotkey高手群 Hello_srf开发的柚子输入法,融合了承影和jip输入法的理念。 影子输入法为开源、绿色、安全的输入法。请放心使用!"
	If Adminfg&&!(A_IsAdmin || RegExMatch(DllCall("GetCommandLine", "Str"), " /restart(?!\S)")){
		Try	{
			If A_IsCompiled
				Run *RunAs "%A_ScriptFullPath%" /restart
			Else
				Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
		}
		ExitApp
	} Else If (A_IsAdmin)
		YzIni.Settings["Adminfg"]:=1
	FileDelete, temp32.exe
	FileDelete, temp64.exe
	If (Source="Gitee")
		Sourceurl:="https://gitee.com/orz707/shadow/raw/master"
	Else
		Sourceurl:="https://autohotkey.oss-cn-qingdao.aliyuncs.com/AutoAHKScript/Scripts/yz"
	If !FileExist(DllFolder "\SQLite3.dll"){
		Progress, B2 ZH-1 ZW-1 FS12, %DllFolder%\SQLite3.dll不存在！`n正在下载，请稍后...
		If !URLDownloadToFile(A_PtrSize=4?Sourceurl "/Lib/Dll_x86/SQLite3.dll":"https://autohotkey.oss-cn-qingdao.aliyuncs.com/AutoAHKScript/Scripts/yz/Lib/Dll_x64/SQLite3.dll", DllFolder "\SQLite3.dll"){
			Progress, Off
			MsgBox, 16, 错误, SQLite3.dll下载失败！`n请手动下载后放在%DllFolder%。
			ExitApp
		}
		Progress, Off
	}
	If (!FileExist("Lib\yz.icl"))
		URLDownloadToFile("https://autohotkey.oss-cn-qingdao.aliyuncs.com/AutoAHKScript/Scripts/yz/Lib/yz.icl", "Lib\yz.icl")
	If (!FileExist(main)){
		tvar:=1
		If (FileExist("ciku_demo.db")){
			FileGetSize, var, ciku_demo.db, M
			Runtime:=A_TickCount
			FileCopy, ciku_demo.db, %main%
			If (ErrorLevel){
				Try	{
					If A_IsCompiled
						Run *RunAs "%A_ScriptFullPath%" /restart
					Else
						Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
				}
				ExitApp
			}
			If (var*1000/(A_TickCount-Runtime)<400){
				MsgBox, 64, 提示, 如遇到输入卡顿的现象，可尝试开启内存数据库选项。
			}
		} Else {
			Run, https://www.autoahk.com/archives/15117
			Progress, B2 ZH-1 ZW-1 FS12, 正在下载词库ciku.db
			URLDownloadToFile("https://autohotkey.oss-cn-qingdao.aliyuncs.com/AutoAHKScript/Scripts/yz/ciku_demo.db", "ciku_demo.db")
			Progress, Off
			Goto srf_init
		}
	}
	If (!FileExist("Lib\IMEConverter.exe"))
		URLDownloadToFile(Sourceurl "/Lib/IMEConverter.exe", "Lib\IMEConverter.exe")
	If (!FileExist("Lib\CloudInput.exe"))
		URLDownloadToFile(Sourceurl "/Lib/IMEConverter.exe", "Lib\CloudInput.exe")

	;画主窗口
	Gosub TRAYMENU
	Gosub LoadLogo
	ChangeDB()
	Gosub module_functions
	Gosub houxuankuangguicreate
	valueindex:=Traditional?5:2, SendDelaymode:=(SendFromClip?"{Fast}":(SendDelay?"{Text}{Delay," SendDelay*10 ",0}":""))
	waitnum:=srf_mode:=Learnfg:=0, ClipSaved:="", MethodTable:={sanma:"sanma",lianda:"lianda"}, AppIMEtable:={}, history_field_array:={}
	pinyinec:={pinyin:"全拼",xhsp:"小鹤双拼",zrmsp:"自然码双拼",abcsp:"ABC双拼",sgsp:"搜狗双拼",wrsp:"微软双拼"}, pinyince:={}, customspjm:={}
	Function_for_select:={}, save_field_array:={}, SQL_buffer:={}, srf_Plugins:={}, srf_last_input:={}, srf_Custom_Func:={}
	#Include *i Lib\usercustoms.ahk
	Try srf_Custom_Func:=JSON.Load(CustomFuncName)
	mhyRegExstr:=(mhy_zh?"z":"") (mhy_sh?"s":"") (mhy_ch?"c":"") (mhy_ang?"a":"") (mhy_eng?"e":"") (mhy_ing?"i":"")
	shurulei:=MethodTable[Inputscheme]?MethodTable[Inputscheme]:Inputscheme~="sp$|pinyin"?"pinyin":"xingma", pinyinlist:=""
	Gosub Registrationfuncandlabel
	Gosub Registrationhotkey
	For Key,Value In customspjm
		pinyinec[Key]:=customspjm[Key,"1"], pinyince[customspjm[Key,"1"]]:=Key
	For Key,Value In pinyinec
		pinyince[Value]:=Key, pinyinlist .= "|" Value
	
	If (tvar){
		Progress, B2 ZH-1 ZW-1 FS12, 词库初始化。。。
		DB.GetTable("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('sqlite_sequence','hebing')",Result)
		Loop % Result.RowCount
			DB.Exec("CREATE INDEX IF NOT EXISTS ""sy_" Result.Rows[A_Index,1] """ ON """ Result.Rows[A_Index,1] """ (""" (Result.Rows[A_Index,1]="pinyin"?"jp":"key") """);")
		Progress, Off
		Gosub cikuManager
		Gosub Option
		Gosub Help
	}
	srf_all_input:="yingzi"
	Gosub srf_tooltip
	Gosub srf_value_off
	If (fuzhuma)	; 载入辅助码
		Gosub Loadfuzhuma
	SetTimer, AppImeAutoSwitch, 150
	If (CloudInput&&Inputscheme~="pinyin|sp$")
		Try	{
			Run, % "Lib\CloudInput.exe " DllCall("GetCurrentProcessId") " " YzIni["Hidden","CloudApi"], , , tvar
			srf_Plugins["CloudInput",1]:=tvar
		}
	If Autoupdatefg
		SetTimer, srfAutoupdatefg, -10
	If A_Args[1]
		Gosub help
Return

AppImeAutoSwitch(){
	Critical, Off
	static history_activepid:=0
	global yzPID, AppIMEtable, Different, srf_mode, IMEmode, srf_inputing, SendDelay, SendFromClip, SendDelaymode
	WinGet, activepid, PID, A
	If (activepid=yzPID)||(history_activepid=activepid)
		Return
	If (Different){
		WinGetClass, activeclass, A
		WinGet, activeexe, ProcessName, A
		If (history_activepid)
			AppIMEtable[history_activepid]:=srf_mode, cleanappimetable(history_activepid)
		SendDelaymode:=(SendFromClip?"{Fast}":(SendDelay?"{Text}{Delay," SendDelay*10 ",0}":""))
		Switch (checkactivewindow(activeclass,activeexe)^srf_mode){
			Case 1:
				Gosub srfSwitch
			Case -2,-1:
				If (AppIMEtable[activepid]=""){
					AppIMEtable[activepid]:=IMEmode-1
					If (srf_mode!=IMEmode-1)
						Gosub srfSwitch
				} Else If (AppIMEtable[activepid]!=srf_mode)
					Gosub srfSwitch
			Case -4,-3:
				SendDelaymode:="{Fast}"
				If (!srf_mode)
					Gosub srfSwitch
		}
	}
	If (!srf_inputing)
		SetTimer, ToolTipInputStatus, -100
	history_activepid:=activepid
}
checkactivewindow(arr*){
	global IMECnWindows,IMEEnWindows,ClipWindows
	If (IMEEnWindows)
		For Key,Value In arr
			If Value In %IMEEnWindows%
				Return 0
	If (ClipWindows)
		For Key,Value In arr
			If Value In %ClipWindows%
				Return -3
	If (IMECnWindows)
		For Key,Value In arr
			If Value In %IMECnWindows%
				Return 1
	Return -1
}
cleanappimetable(pid){
	global AppIMEtable
	static historypid
	Process, Exist, %historypid%
	If (!ErrorLevel)
		AppIMEtable.Delete(historypid)
	historypid:=pid
}
ChangeDB(){
	global DB
	DB.GetTable("SELECT 1 FROM sqlite_master WHERE type='table' AND tbl_name='pinyin' AND NOT instr(sql,'jp')", Result)
	If (Result.Rows[1,1]){
		MsgBox, 308, 词库调整, 本次更新将调整pinyin词库结构，优化文件占用空间，如有重要信息，请注意备份词库！`n是否继续？
		IfMsgBox, No
			ExitApp
		Progress, B2 ZH-1 ZW-1 FS12, 调整词库中，请稍后...
		DB.Exec("BEGIN TRANSACTION;")
		DB.Exec("DROP TABLE IF EXISTS 'main'.'hebing';")
		DB.Exec("CREATE TABLE 'main'.'hebing' (""jp"" TEXT,""Key"" TEXT,""Value"" TEXT,""weight"" INTEGER DEFAULT 0);")
		DB.Exec("INSERT INTO 'main'.'hebing' SELECT szm(Key),Key,Value,max(weight) FROM 'main'.'pinyin' GROUP by Key,Value ORDER by ROWID;")
		DB.Exec("DROP TABLE 'main'.'pinyin';ALTER TABLE 'main'.'hebing' RENAME TO 'pinyin';")
		DB.Exec("CREATE INDEX 'main'.'sy_pinyin' ON 'pinyin' ('jp');")
		DB.Exec("DROP TABLE IF EXISTS 'main'.'jianpin';")
		DB.Exec("COMMIT TRANSACTION;")
		DB.Exec("VACUUM")
		Progress, Off
		MsgBox 调整完成
	}
	DB.GetTable("SELECT tbl_name,count(*) as n FROM sqlite_master WHERE name!='sqlite_sequence' GROUP by tbl_name HAVING n=1",Result)
	If (Result.RowCount){
		Loop % Result.RowCount
			DB.Exec("CREATE INDEX ""sy_" Result.Rows[A_Index,1] """ ON """ Result.Rows[A_Index,1] """ (""" (Result.Rows[A_Index,1]="pinyin"?"jp":"key") """)")
	}
}

Loadfuzhuma:
ReLoadfuzhuma:
	; srf_fzm_table:={}, 
	srf_fzm_fancha_table:={}
	If !FileExist("Lib\@fzm.txt"){
		fuzhuma:=0
		GuiControl, 3:, fuzhuma, 0
		If (A_ThisLabel="ReLoadfuzhuma")
			MsgBox, 48, 提示, 辅助码文件不存在，请在Lib目录下放置辅助码文件@fzm.txt，格式如下：`n吖=k`n阿=e`n啊=k`n文本编码为UTF-8-Bom或ANSI
	} Else {
		FileRead, tvar, Lib\@fzm.txt
		Loop, Parse, tvar, `n, `r
		{
			If (A_LoopField="")
				Continue
			srf_fzm_fancha_table[(tarr:=StrSplit(A_LoopField, "="))[1]]:=tarr[2]
			; srf_fzm_table[tarr[2]] .= "|" tarr[1]
		}
		; For Key, tvar in srf_fzm_table
		; 	srf_fzm_table[Key]:="(" Trim(tvar, "|") ")"
		Key:=tvar:=""
	}
Return
FuncHotkey:
	srf_all_input:=srf_func_hk[A_ThisHotkey] func_key, srf_inputing:=1
	Gosub srf_tooltip
Return
Registrationfuncandlabel:	; 注册内置函数
	srf_func_table:={}, srf_func_hk:={}
	Hotkey If, srf_mode
	; For Key,Value In {magic:"magic", run:"run"}
	; 	If RegExMatch(srf_Custom_Func[Key],"^&\K.+$",Match){
	; 		Try {
	; 			Hotkey, %Match%, FuncHotkey, On
	; 			srf_func_table[Value]:=Key, srf_func_hk[Match]:=Key
	; 		}
	; 	} Else
	; 		srf_func_table[srf_Custom_Func[Key]?srf_Custom_Func[Key]:Value]:=Key
	For Key,Value In srf_Default_Func
		If RegExMatch(srf_Custom_Func[Value[1]],"^&\K.+$",Match){
			srf_func_table[Value[1]]:=Func(Key)
			Try {
				Hotkey, %Match%, FuncHotkey, On
				srf_func_hk[Match]:=Value[1]
			}
		} Else
			srf_func_table[srf_Custom_Func[Value[1]]?srf_Custom_Func[Value[1]]:Value[1]]:=Func(Key)
	Hotkey If
	For Key,Value In srf_func_hk
		Hotkey, %Key%, FuncHotkey, On
Return

;备份
Backup(){
	If !FileExist("backups")
		FileCreateDir, backups
	Loop, Files, %A_ScriptDir%\*.*
		If (A_LoopFileFullPath~=StrReplace("i)" A_ScriptDir "\","\","\\") "[^\\]+\.(exe|ahk|db|ini)")
			FileCopy, %A_LoopFileFullPath%, % StrReplace(A_LoopFileFullPath,A_ScriptDir,A_ScriptDir "\backups"), 1
	FileCopyDir, %A_ScriptDir%\Lib, %A_ScriptDir%\backups\Lib, 1
}
;更新
srfAutoupdatefg:
srfUpdate:
	;获取更新信息
	If (!DllCall("Wininet.dll\InternetCheckConnection", "Str", Sourceurl, "UInt", 0x1, "UInt", 0x0, "Int")){
		If (A_ThisLabel="srfUpdate")
			MsgBox, 16, 检查更新, 网络异常,将无法更新脚本！, 5
	} Else {
		If !RegExMatch(var:=SendRequest(Sourceurl "/yz.ini"), "i)Version=\K[\d\.]+", UpdateVersion){
			If (A_ThisLabel="srfUpdate")
				MsgBox, 16, 检查更新, 获取版本信息失败！, 5
		} Else If (Version>=UpdateVersion){
			If (A_ThisLabel="srfUpdate")
				MsgBox, 64, 检查更新, 影子输入法已经是最新版本了。, 5
		} Else If (Version<UpdateVersion){
			MsgBox, 36, 检查更新, % "检测到影子输入法有新版本`n`n" Version "`t版本更新后=>`t" UpdateVersion "`n`n更新说明：`n" RegExReplace(SendRequest("https://gitee.com/orz707/shadow/raw/master/change.txt"), "im).*v" RegExReplace(UpdateVersion,"^(\d+\.\d+.\d+)(\.\d)?","$1") "([^" Chr(2) "]+).*", "$1") "`n是否更新到最新版本？"
			IfMsgBox Yes
			{
				Backup()
				If FileExist("影子输入法32.exe")
					FileMove, 影子输入法32.exe, temp32.exe
				If FileExist("影子输入法64.exe")
					FileMove, 影子输入法64.exe, temp64.exe
				downloadfilenum:=0
				If !URLDownloadToFile(Sourceurl "/影子输入法32.exe", "影子输入法32.exe"){
					If FileExist("temp32.exe")
						FileMove, temp32.exe, 影子输入法32.exe
					MsgBox, 48, 检查更新, 下载影子输入法32位失败, 2
				} Else
					downloadfilenum++
				If !URLDownloadToFile(Sourceurl "/影子输入法64.exe", "影子输入法64.exe"){
					If FileExist("temp64.exe")
						FileMove, temp64.exe, 影子输入法64.exe
					MsgBox, 48, 检查更新, 下载影子输入法64位失败, 2
				} Else
					downloadfilenum++
				RegExMatch(var,"i)UpdateFile=\K.+", UpdateFile), var:=""
				Loop, Parse, UpdateFile, `,
				{
					If (A_LoopField~="i)\.exe$"){
						tvar:=RegExReplace(A_LoopField,".*/")
						Process, Exist, %tvar%
						If (ErrorLevel)
							Process, Close, %ErrorLevel%
					}
					If (A_LoopField~="(IMEConverter.exe|yz.icl)"){
						If !URLDownloadToFile("https://autohotkey.oss-cn-qingdao.aliyuncs.com/AutoAHKScript/Scripts/yz/" A_LoopField, StrReplace(A_LoopField,"/","\"))
							MsgBox, 48, 检查更新, % "下载" RegExReplace(A_LoopField,".*/") "失败", 2
					} Else If !URLDownloadToFile(Sourceurl "/" A_LoopField, StrReplace(A_LoopField,"/","\"))
						MsgBox, 48, 检查更新, % "下载" RegExReplace(A_LoopField, ".*/") "失败", 2
				}
				If (downloadfilenum>0){
					Version:=YzIni.Version["Version"]:=UpdateVersion, YzIni.Save()
					If A_IsCompiled
						Run "%A_ScriptFullPath%" /restart update
					Else
						Run "%A_AhkPath%" /restart "%A_ScriptFullPath%" update
					ExitApp
				}
			}
		}
	}
Return
; 界面
;------------------------------------------------------------------------------------------------------------------------
; 选词框gui、ToolTip
houxuankuangguicreate:
	Height:=60
	If (Caret="")
		Caret:={X:A_ScreenWidth//2-A_ScreenWidth//8, Y:A_ScreenHeight-20-Height*(InStr(ToolTipText,"`n")?2.5:4)}
	If (ToolTipStyle=1)
		GdipText("",,"Shutdown"), @TSF:=ToolTip(1, "", "Q1 B" BackgroundColor " T" TextColor " S" FontSize, TextFont, FontBold)
	Else
		GdipText(""), ToolTip()
		; , ToolTip(2, "", "Q1 B" BackgroundColor " T" TextColor " S" FontSize " F" TextFont)
Return

;托盘按钮
TRAYMENU:
	Menu, Tray, NoStandard                                         ;去掉标准托盘按钮
	Menu, Tray, DeleteAll                                              ;清空托盘按钮
	Menu, Tray, Add, 词库管理, cikuManager
	Menu, Tray, Icon, 词库管理, Lib\yz.icl, 3
	Menu, Tray, Add
	Menu, Tray, Add, 选项, Option
	Menu, Tray, Icon, 选项, Lib\yz.icl, 4
	Menu, Tray, Add, 更新, srfUpdate
	Menu, Tray, Icon, 更新, Lib\yz.icl, 5
	Menu, Tray, Add, 帮助, Help
	Menu, Tray, Icon, 帮助, Lib\yz.icl, 6
	
	Menu, Tray, Add
	Menu, Tray, Add, 禁用, srfsuspend
	Menu, Tray, Icon, 禁用, Lib\yz.icl, 14
	Menu, Tray, Add, 重启, srfreload
	Menu, Tray, Icon, 重启, Lib\yz.icl, 8
	Menu, Tray, Add, 退出, EXIT
	Menu, Tray, Icon, 退出, Lib\yz.icl, 9
	Menu, Tray, Default, 词库管理
	Menu, Tray, Tip, 影子
	Menu, Tray, Icon, Lib\yz.icl, 1, 1
	Menu, Tray, Click, 2
	Menu, MyContextMenu, Add, 新建(&N), NewRow
	Menu, MyContextMenu, Add, 删除(&D), DelRow
	Menu, MyContextMenu, Add, 刷新(&R), Refresh2
	Menu, MyContextMenu, Add, 撤销(&U), Revoke
	Menu, BarMenu, Add, 100/页, fynumset
	Menu, BarMenu, Add, 500/页, fynumset
	Menu, BarMenu, Add, 1000/页, fynumset
	Menu, appContextMenu, Add, 剪贴板`tAlt+D, 剪贴板
	Menu, appContextMenu, Add, 中文`tAlt+C, 中文
	Menu, appContextMenu, Add, 英文`tAlt+E, 英文
	Menu, appContextMenu, Add, 删除`tDel, 删除
Return

;加载logo
LoadLogo:
SetLogoSize:
	WinGetPos,,,,TrayWnd_Height,ahk_class Shell_TrayWnd
	Gui, 2:Destroy
	If (A_OSVersion="WIN_XP"){
		Gui, 2:-Caption +AlwaysOnTop +ToolWindow -DPIScale +HwndHGui2
		If FileExist("yz.png")
			Gui, 2:Add, Picture, , yz.png
		Else
			Gui, 2:Add, Picture, Icon1, Lib\yz.icl
		Gui, 2:Show, % "NA x" (YzIni["Hidden","X"]?YzIni["Hidden","X"]:A_ScreenWidth-A_ScreenWidth//5-(64*LogoSize//200)) " y" (YzIni["Hidden","Y"]?YzIni["Hidden","Y"]:A_ScreenHeight-TrayWnd_Height-(64*LogoSize//100))
		WinSet, TransColor, F0F0F0 255, ahk_id%HGui2%
	} Else {
		If (!pToken)&&(!pToken:=Gdip_Startup()){
			MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
			ExitApp
		}
		If FileExist("yz.png")
			pBitmap:=Gdip_CreateBitmapFromFile("yz.png")
		Else
			pBitmap:=Gdip_BitmapFromBase64(""
			. "iVBORw0KGgoAAAANSUhEUgAAAC8AAAA+CAYAAAC7rUKSAAANFklEQVRogX1aacitVRV+1v6OwY3UFGkk"
			. "LArjqpGaP+RKiESFaDdQsCQhMyLKikKrX/6JaKABo4GKbFAsIygrM9NyzqFUMEiLqxGaXJMGpTSzzn5i"
			. "772m/Z7v6/34eM95p7PW2s961vTK3jechlIKtspW3/f/rbbX7yKQIihSIFtb43v+L2XsQQDtMwCRg0G+"
			. "BJDDpeBQALv6aeBfJP8O4EGI7Ce5n5UAK/qu/dUKkqjrNSraqTXquqLWinU71q5dV6zrGqsmVBfMBOrC"
			. "lFlA/W6K9L98vsmLciJEXgPBiQCOE5HDkLd2EdHv51DkSRC/F8FtJG4Uwc0g9tNuaVboFwp22lbtXAgu"
			. "/R5ZWLdMFrbjXZBdArwfkLcAOGo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9OpUXZ0CE5rmH3hXoicJVJOBOUnJlB+4UIDQrT0Uso1sZDglRbIormiWFdu"
			. "n4bUaRDC3iBG/LnpEdp5qE7tM/39WwGcBuIYCL4HRiq9UXzLqI6iVpho9FKMVwOcv6mcjg0wx77DNS8b"
			. "fd65/A/Bp20Y+B5BOVMErwfKPfNrLYKSOgmTAjLB6BPGLD7AqGkua0OMih1gM7WscwI0ta2i7nCNnNyv"
			. "EcExAnw0UGPl3TxZX0CnbecAPNjc1saiTK+2THsVongHqmYHTdjbJjjMpXSizyHghSLyntFswiSwJXOu"
			. "wNxi2Rvcn6JYngksZgMlXlSwLm+dR+VL2kL+XN18U/1b5ItS8C6RUj3ft6w0N51ywS14NVOaMRP4/G8r"
			. "VpY8Or8TMyuACS5ps/ShILPKlwX41pTAZWf21fOlPDxT2kb8yWSihNIHaq2J04vbNuUuOltqRVbVvmCA"
			. "+5MADoPgalB+CeDhOY2JNjnBg6TI7g7JhHFjiq6pvxnV73zKzm4nv5fR/p19MtIfIip4f1OiNrzW8aph"
			. "m5q0YmSw10sFOB2Ut4m0ebrcAeCHfTonPX1oL73tliKvA3EOicM6RMaLDK1lp+lzxfgyChMZBcoDOdPc"
			. "zt+mAV0fqLnFqxqijTNrL/Bq762LvmbSl/9XlHK6QmdLgD2A7BncX/7Zwj5bV9QB4a+MDCGLCReJno1H"
			. "AfzYlFkmKPm77wdVQnGO2Rn1u7+sOYbfN0eES84zKqdnDYVSy9smJJ60RSqNTKOQ1i65PnnBLLQXLLO/"
			. "FacnVndSpBcW4g29zq+twf/49JA8aE7Hl7we+Q2cZr25JThjJ0fdyHkT83W2qfrSg71RVBmvRdnbeTXe"
			. "zvvwcJOIfvFwLyijQ40SXYOcPthn4B3t9VxvLy63jegeMajE20aZFk3wOkVbPf8VkhcAfDxbekKqFyap"
			. "OnSeNxbHowJ8EMDXNiVeyDv9RmxtrBO4tdzOgKa98D7iNxrtl9XPkPJ1SHkz0Fp48orebDJh80LY/BfS"
			. "5km/g8jdgFwLwQ+EfHL+5e3kT+8rJDICiP8BCkrJxs8fqYQAAAAASUVORK5CYII=")
		PW:=Gdip_GetImageWidth(pBitmap), PH:=Gdip_GetImageHeight(pBitmap)
		Gui, 2:-Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow -DPIScale +HwndHGui2
		Gui, 2:Show, NA
		hbm:=CreateDIBSection(PW*LogoSize//100, PH*LogoSize//100), hdc:=CreateCompatibleDC()
		obm:=SelectObject(hdc, hbm), G:=Gdip_GraphicsFromHDC(hdc), Gdip_SetInterpolationMode(G, 7)
		Gdip_DrawImage(G, pBitmap, 0, 0, PW*LogoSize//100, PH*LogoSize//100, 0, 0, PW, PH)
		UpdateLayeredWindow(HGui2, hdc, YzIni["Hidden","X"]?YzIni["Hidden","X"]:A_ScreenWidth-A_ScreenWidth//5-(PW*LogoSize//200), YzIni["Hidden","Y"]?YzIni["Hidden","Y"]:A_ScreenHeight-TrayWnd_Height-(PH*LogoSize//100), PW*LogoSize//100, PH*LogoSize//100)
		SelectObject(hdc, obm), DeleteObject(hbm), DeleteDC(hdc), Gdip_DeleteGraphics(G), Gdip_DisposeImage(pBitmap)
		pToken:=Gdip_Shutdown(pToken)
	}
	If (A_ThisLabel="SetLogoSize"){
		If !(srf_mode)
			Gui, 2:Hide
		Return
	}
	Gui, 2:Hide

	; 加载数据库
	LoadDB:
	If (DB._Handle)
		DB.CloseDB()
	DB:="", DB:=new SQLiteDB
	If (MemoryDB){
		Suspend, On
		Progress, B2 ZH-1 ZW-1 FS12, 载入内存数据库中，请稍后...
		If !(DB.OpenDB("")&&DB.LoadOrSaveDb(main)){
			MsgBox, 16, 数据库错误, % "消息:`t" DB.ErrorMsg "`n代码:`t" DB.ErrorCode
			ExitApp
		}
		Suspend, Off
		Progress, Off
	} Else If !DB.OpenDB(main){
		MsgBox, 16, 数据库错误, % "消息:`t" DB.ErrorMsg "`n代码:`t" DB.ErrorCode
		ExitApp
	}
	DB.CreateScalarFunc("REGEXP", 2, RegisterCallback("SQLiteDB_RegExp", "C"))
	DB.CreateScalarFunc("szm", 1, RegisterCallback("shouzimu", "C"))
	; DB.CreateScalarFunc("erjiayi", 2, RegisterCallback("erjiayi", "C"))
	DB.Exec("DROP TABLE IF EXISTS 'main'.''")
	DB.AttachDB(extend, "extend")
	If (extend!=main)&&DB.GetTable("SELECT name FROM sqlite_master WHERE type='table' AND tbl_name IN ('English','functions','hotstrings','customs','symbol')",TableInfo){
		Loop % TableInfo.RowCount {
			If (TableInfo.Rows[A_Index,1]="English"), TableName:=TableInfo.Rows[A_Index,1]
				_SQL = CREATE TABLE 'extend'.'English' ("key" TEXT COLLATE NOCASE,"weight" INTEGER DEFAULT 0);
			Else If (TableName ~= "functions|hotstrings|symbol|customs")
				_SQL = CREATE TABLE 'extend'.'%TableName%' ("key" TEXT,"value" TEXT,"comment" TEXT);
			If DB.Exec(_SQL)
				DB.Exec("INSERT INTO 'extend'.'" TableName "' SELECT * FROM 'main'.'" TableName "'"), DB.Exec("DROP TABLE 'main'.'" TableInfo.Rows[A_Index, 1] "'")
		}
	}
Return

96GuiEscape:
	99GuiEscape:
	Gui Hide
Return

Help:
	Gui, 96:Destroy
	If DllCall("Wininet.dll\InternetCheckConnection", "Str", "https://gitee.com/orz707/shadow/wikis/pages", "UInt", 0x1, "UInt", 0x0, "Int"){
		Gui, 96:-DPIScale
		Gui, 96:Margin, 0, 0
		Gui, 96:Add, ActiveX, % "w" Min(A_ScreenWidth-100, 1200) " h" Min(A_ScreenHeight-100, 800) " vwb", Shell.Explorer
		If (A_Args[1]="update"), A_Args:=[] {
    		wb.Navigate("https://gitee.com/orz707/shadow/wikis/pages?sort_id=1811043&doc_id=434278")
			TrayTip, 影子输入法, 更新完成, 3
		} Else
			wb.Navigate("https://gitee.com/orz707/shadow/wikis/pages")
		Gui, 96:Show, , 影子输入法 帮助
		Return
	}
	Gui, 96:Margin, 20, 20
	Gui, 96:Add, Picture, xm w13 h-1 Icon1, Lib\yz.icl
	Gui, 96:Font, s11 Bold, %GUIFont%
	Gui, 96:Add, Text, x+10 yp, 简易帮助
	Gui, 96:Font
	Gui, 96:Font, s11, %GUIFont%
	Gui, 96:Add, Text, y+5, LShift切换输入模式
	Gui, 96:Add, Text, y+5, Space首选上屏, Enter英文字符上屏
	Gui, 96:Add, Text, y+5, /键 内置功能键
	Gui, 96:Add, Text, y+5, 1、2、3、……、，、。候选上屏
	Gui, 96:Add, Text, y+5, Ctrl + 1、2、3、……调节对应项到首选，`n长按调至指定位置
	Gui, 96:Add, Text, y+5, Ctrl + Alt + 1、2、3、……删除对应词条
	Gui, 96:Add, Text, y+5, Left、Right、Ctrl + 字母 调整插入位置
	Gui, 96:Add, Text, y+5, Ctrl + = 快捷造词
	Gui, 96:Add, Text, y+5, Ctrl + Shift + Alt + F1 帮助
	Gui, 96:Add, Text, y+5, 在选项、词库管理的控件处停留0.5秒`n显示详细说明
	Gui, 96:Add, Text, y+5, 选项 - 控制 - 命令管理 - 模式切换`n有更多便捷的设置
	Gui, 96:Add, Picture, xm y+20 w13 h-1 Icon11, Lib\yz.icl
	Gui, 96:Font, s11 Bold, %GUIFont%
	Gui, 96:Add, Text, x+10 yp, 详细帮助
	Gui, 96:Font
	Gui, 96:Font, s11, %GUIFont%
	Gui, 96:Add, Link, y+5, <a href="https://gitee.com/orz707/shadow/wikis">影子帮助文档</a>
	Gui, 96:Show, , 影子输入法 帮助
Return